package com.kelp.codetoolkit.utils

import java.util.regex.Pattern


/**
 * @author: liuyuebai
 * @date: 2024/8/2 18:00
 * @description:
 */
object NameHandleUtil {

    private var to_hump: Pattern?= Pattern.compile("[-_]([a-z0-9])")
    private var to_hump_one: Pattern?= Pattern.compile("[-_]([a-z0-9])")
    private var to_line:Pattern?= Pattern.compile("[A-Z]+")

    /**
     * 首字母大写
     */
    fun initialUpperCase(value:String):String{
        if (value.isBlank()){
            return value
        }
        return value.replaceFirst(value[0],value[0].uppercaseChar())
    }

    /**
     * 首字母小写
     */
    fun initialLowerCase(value:String?):String{
        if (value.isNullOrBlank()){
            return ""
        }
        return value.replaceFirst(value[0],value[0].lowercaseChar())
    }

    /**
     * 驼峰
     */
    fun convertCamelName(name:String):String{
        if (name.isBlank()){
            return name
        }
        val input = name.lowercase()
        val matcher = to_hump?.matcher(input)
        val buffer = StringBuffer()
        if (matcher != null) {
            while (matcher.find()){
                matcher.appendReplacement(buffer, matcher.group(1).uppercase())
            }
        }
        matcher?.appendTail(buffer)
        return buffer.toString()
    }

    /**
     * 驼峰
     */
    fun convertCamelNameTwo(name:String):String{
        if (name.isBlank()){
            return name
        }
        val input = name.lowercase()
        val matcher = to_hump_one?.matcher(input)
        val buffer = StringBuffer()
        if (matcher != null) {
            while (matcher.find()){
                matcher.appendReplacement(buffer, matcher.group(1).uppercase())
            }
        }
        matcher?.appendTail(buffer)
        return buffer.toString()
    }

    fun convertClassName(tableName:String):String{
        val camelName = convertCamelName(tableName)
        return initialUpperCase(camelName)
    }

    fun camelCaseToUnderscore(str:String):String{
        val builder = StringBuilder()
        for (i in str.indices) {
            val char = str[i]
            if (i > 0 && char.isUpperCase()) {
                builder.append('_')
            }
            builder.append(char.toLowerCase())
        }
        return builder.toString()
    }
}